<template>
  <el-container>
    <el-main class="login-container">
      <el-row align="middle" style="height:100%">
        <el-col>
          <el-row justify="center">
            <el-card class="login-box" border shadow="never">
              <el-row justify="center" style="margin-top: 20px;">
                <el-text class="mx-1" style="font-size: 26px;color: black;">
                  欢迎访问任务管理系统
                </el-text>
              </el-row>

              <el-form label-position="top" label-width="auto" :model="loginForm">
                <el-form-item label="用户名：" label-position="top">
                  <el-input v-model="loginForm.username" @keyup.enter="handleSubmit">
                    <template #prefix>
                      <el-icon>
                        <UserFilled />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="密码：" label-position="top">
                  <el-input type="password" v-model="loginForm.password" @keyup.enter="handleSubmit" show-password>
                    <template #prefix>
                      <el-icon>
                        <Lock />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button plain style="width: 100%;">获取验证码</el-button>
                </el-form-item>
                <el-form-item style="padding-top: 7px;">
                  <el-button type="primary" @click="handleSubmit" style="width: 100%;">登录</el-button>
                </el-form-item>
              </el-form>

              <el-row justify="center">
                <el-text class="mx-1" size="small">忘记密码？</el-text>
                <el-text class="mx-1" type="primary" size="small">联系管理员</el-text>
              </el-row>
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { EnumDef } from '../lib/enum-def';
import { encryptAES } from '../utils/aes';
import { ref, reactive, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { UserFilled, Lock } from '@element-plus/icons-vue';

const store = useStore();
const router = useRouter();
const { proxy: { $axios, $utils } } = getCurrentInstance();
const {
  loginForm,
  handleSubmit
} = useLoginTemp();

function useLoginTemp() {
  const loginForm = reactive({
    username: '',
    password: ''
  });
  const isSubmitting = ref(false);

  const validate = () => {
    if (!loginForm.username.trim()) return '请输入用户名';
    if (loginForm.password.length < 6) return '密码至少6位';
    return null;
  }

  const handleSubmit = async () => {
    const validationError = validate();
    if (validationError) {
      ElMessage.warning(validationError);
      return;
    }

    const path = '/api/auth/login';
    const reqHeader = {
      headers: { 'Content-Type': 'application/json' }
    };
    const reqParams = {
      username: loginForm.username,
      password: encryptAES(loginForm.password)
      // remember: true
    };

    isSubmitting.value = true
    try {
      const { code, data } = await $axios.post(path, reqParams, reqHeader);

      if (code === 200 && data?.token.length) {
        router.push({ path: '/tasks' });
        store.commit('user/setUser', data?.userinfo || {});
        localStorage.setItem('token', data?.token);
        enumFormater(data.enumType, data.enumData);
      } else {
        ElMessage.error('用户名或密码错误');
      }
    } catch (err) {
      console.error('登录失败:', err);
    } finally {
      isSubmitting.value = false;
    }
  }

  function enumFormater(types = [], data = []) {
    const formater = ['dict_value=>value', 'dict_label=>label', 'dict_name=>name'];
    const enumDefs = {};

    types.forEach(row => {
      const children = data.filter(col => row.type_code === col.type_code) || [];
      const members = $utils.renameArrayProp(children, formater, 'members');
      enumDefs[row.type_code] = new EnumDef(members);
    });
    store.commit('enums/setEnums', enumDefs);
  }

  return {
    loginForm,
    handleSubmit
  };
}
</script>

<style>
.login-container {
  width: 100vw;
  height: 100vh;
  /* background-color: #e5e9ec; */
  background-image: -moz-linear-gradient(50deg, rgb(245, 234, 222) 0%, rgb(218, 213, 210) 13%, rgb(191, 191, 197) 35%, rgb(137, 158, 177) 71%, rgba(82, 125, 157, 0.8) 100%);
  background-image: -webkit-linear-gradient(50deg, rgb(245, 234, 222) 0%, rgb(218, 213, 210) 13%, rgb(191, 191, 197) 35%, rgb(137, 158, 177) 71%, rgba(82, 125, 157, 0.8) 100%);
  background-image: -ms-linear-gradient(50deg, rgb(245, 234, 222) 0%, rgb(218, 213, 210) 13%, rgb(191, 191, 197) 35%, rgb(137, 158, 177) 71%, rgba(82, 125, 157, 0.8) 100%);
  background: url('../../public/mountain-top-983890.jpg');
}

.login-box {
  width: 432px;
  padding-bottom: 20px;
}
</style>